package bbs;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import util.DB;

public class ArticleCategoryDAO {

    private static ArticleCategory makeArticleCategory(ResultSet rs) throws Exception {
        ArticleCategory obj = new ArticleCategory();
        obj.setId(rs.getInt("Id"));
        obj.setBoardId(rs.getInt("boardId"));
        obj.setName(rs.getString("name"));
        obj.setCount(rs.getInt("count"));
        return obj;
    }

    public static ArrayList<ArticleCategory> selectAll(int boardId) throws Exception {
        String sql = "EXEC bbs.articleCategorySelectByBoardId ?";
        try (Connection con = DB.getConnection();
             PreparedStatement stmt = con.prepareStatement(sql)) {
            stmt.setInt(1, boardId);
            try (ResultSet rs = stmt.executeQuery()) {
                ArrayList<ArticleCategory> list = new ArrayList<>();
                while (rs.next())
                    list.add(makeArticleCategory(rs));
                return list;
            }
        }
    }

    public static void insert(int boardId, String name) throws Exception {
        String sql = "INSERT bbs.[ArticleCategory] ([boardId], [name]) VALUES (?, ?)";
        try (Connection con = DB.getConnection();
             PreparedStatement stmt = con.prepareStatement(sql)) {
            stmt.setInt(1, boardId);
            stmt.setString(2, name);
            stmt.executeUpdate();
        }
    }

    public static void update(int id, String name) throws Exception {
        String sql = "UPDATE bbs.[ArticleCategory] SET [name]=? WHERE [id]=?";
        try (Connection con = DB.getConnection();
             PreparedStatement stmt = con.prepareStatement(sql)) {
            stmt.setString(1, name);
            stmt.setInt(2, id);
        }
    }

    public static void delete(int[] idList) throws Exception {
        String sql = "DELETE bbs.[ArticleCategory] WHERE [id] = ?";
        try (Connection con = DB.getConnection();
             PreparedStatement stmt = con.prepareStatement(sql)) {
            for (int id : idList) {
                stmt.setInt(1, id);
                stmt.executeUpdate();
            }
        }
    }

}
